JavaScript-提升hoisting


Posted by RLun on 2022-10-11

Hoisting觀念

雖然把宣告寫在後面,JavaScript在執行程式之前,會做一個提升(Hoisting)。

Hoisting 特性是宣告提升,並不會給初始值進行提升。

  • 變數從上到下做瀏覽

    console.log(x);   //undefined
    var x = 3;
    console.log(x);   //3
    
  • Hoisting結果

    console.log(x);   //undefined
    var x = 3;
    console.log(x);   //3
    

函式陳述式 (function declaration) 會被提升

  • function,會把function提升最上面

    count();                 //hello
    function count(){
    console.log(’hello!’);
    }
    
  • Hoisting結果

    function count(){
    console.log(’hello!’);
    }
    count();
    

函式表達式Function expression不會被提升,會被提升的式宣告提升

  • function,會把function提升最上面

    count();                             //Uncaught TypeError: count is not a function
    const count = function(){
      console.log(’hello’)
    }
    
  • Hoisting結果,呼叫時執行時並沒有function

    const count;
    count();
    count = function(){
    console.log(’hello!’);
    }
    

補充
函式(function)與變數(variable)同名時,函式優先。

  • function 與 variable 同時存在時

    console.log(count)
    var count;
    function count(){};
    
  • Hoisting結果

    function count(){};
    console.log(count)
    var count;
    

#javascript #js #hoisting #提升 #宣告 #Web







Related Posts

學習 Git (6) - 修改 commit 紀錄 part 1:commit 參數 --amend

學習 Git (6) - 修改 commit 紀錄 part 1:commit 參數 --amend

【Day 1】Docker 基本概念

【Day 1】Docker 基本概念

[Python Excel自動化1]以VBA運行Python操作Excel

[Python Excel自動化1]以VBA運行Python操作Excel


Comments